<template>
  <div class="screen-container" ref="containerComponent">
    <slot></slot>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, onUnmounted, nextTick } from 'vue';
  const props = defineProps({
    options: {
      required: false,
      type: Object
    }
  });
  // 获取dom
  const containerComponent = ref<HTMLElement | null>(null);
  // 获取传入的宽高, 如果没传，就获取当前元素的宽高
  const width = ref(0);
  const height = ref(0);
  // 获取当前屏幕的宽高
  const originalWidth = ref(0);
  const originalHeight = ref(0);
  // 初始化获取宽高
  async function init() {
    // 如果浏览器在进行同步渲染更新的时候，直接执行下面的代码可能会出现问题，所以包含在nextTick里面
    // 等待异步操作执行完，再返回
    await nextTick(() => {
      if (props.options && props.options.width && props.options.height) {
        width.value = props.options.width;
        height.value = props.options.height;
      }
      // window.screen.width, window.screen.height获取设备的屏幕宽高(单位: px)
      originalWidth.value = window.screen.width;
      originalHeight.value = window.screen.height;
    });
  };
  // 更新大小
  function updateSize() {
    // 传了就是这么大，没传就是自动获取当前窗口屏幕大小
    if(width.value && height.value) {
      containerComponent.value!.style.width = `${width.value}px`;
      containerComponent.value!.style.height = `${height.value}px`;
    }else {
      containerComponent.value!.style.width = `${originalWidth.value}px`;
      containerComponent.value!.style.height = `${originalHeight.value}px`;
    }
  };
  // 计算比例
  function updateScale() {
    // 获取当前body宽高
    const currentWidth = document.body.clientWidth;
    const currentHeight = document.body.clientHeight;
    // 获取大屏的最终宽高
    const realWidht = width.value || originalWidth.value;
    const realHeight = height.value || originalHeight.value;
    // 计算 放大/缩小 比例
    const widthScale = currentWidth / realWidht;
    const heightScale = currentHeight / realHeight;
    // 给予赋值
    containerComponent.value!.style.transform = `scale(${widthScale}, ${heightScale})`;
  };
  // 页面比例改变，放大比例改变
  async function onResize() {
    await init();
    updateScale();
  };

  onMounted(async () => {
    // 等待init完全执行完，再继续往下执行
    await init();
    updateSize();
    updateScale();
    window.addEventListener('resize', onResize);
  });

  onUnmounted(() => {
    window.removeEventListener('resize', onResize);
  });
</script>

<style lang="less" scoped>
  .screen-container {
    width: 100%;
    height: 100%;
    position: fixed;
    top: 0;
    left: 0;
    transform-origin: top left;
    z-index: 99;
    font-size: 20px;
    background-image: url('@/assets/img/screen/window.png');
    background-size: 100% 100%;
    background-repeat: no-repeat;
  }
</style>